<?php
namespace Admin\Controller;
use Admin\Model\Menu;
class MenuController extends Controller {
	
	protected $db;
	
		
	
	//构造函数
	public function __init()
	{
        $this->db = new Menu;
	}
	
	
	public function index()
	{
		$data = $this->db->getAll();

	    View::with('data',$data)->make();
	}
	

	public function delmenu(){
		
		Weixin::instance('button')->delButton();
		
	}
	
	public function menu() 
	{

			$menu = Db::table('menu')->get();

			$arr = array();
			
			foreach ($menu as $key => $value) {
				if($value['pid']==0)
				{
					foreach ($menu as $k => $v) {
						if($v['pid']==$value['id'])
						{
							$value['sub_button'][]=$v;
						}
					}
					$arr[] = $value;
				}
			}
			
			$data=array(
				'button'=>$arr
			);
			

			
			$ds = Weixin::instance('button') -> createButton($data);
			p($ds);exit;
			if ($ds) 
			{
				View::ajax(array('code' => 0, 'message' => '创建成功'));
			} 
			else 
			{
				View::ajax(array('code' => 1, 'message' => '创建失败'));
			}
		
	}	
	


    public function add()
    {
        if (IS_POST) 
        {
            if ($this->db->store()) 
            {
                View::ajax(array('code' => 0, 'message' => '添加成功'));
            }
            else
            {
            	View::ajax(array('code' => 0, 'message' => $this->db->getError()));
            }
        }
        else{

            $pid = Q('pid',0);
            $data = $this->db->getAll();

			foreach ($data as $key => $value) {
				
				$cou = Db::table('menu')->where('pid',$value['id'])->get();
				
				$data[$key]['num']=count($cou)>=5?' disabled=""':'';
				if($value['pid']!=0)
				{
					$data[$key]['num']=' disabled=""';
				}
			}
			$count = Db::table('menu')->where('pid',0)->get();
			$data['top']=count($count)>=3?' disabled=""':'';

            View::with('pid',$pid)->with('data',$data)->make();
        }
    }

    public function del()
    {
        if ($this->db->del(Q('post.id'))) 
        {
            View::ajax(array('code' => 0, 'message' => '删除成功'));
        }
        else
        {
            View::ajax(array('code' => 1, 'message' => $this->db->getError()));

        }
    }


    public function edit()
    {
        if (IS_POST) 
        {
            if ($this->db->update()) 
            {
                View::ajax(array('code' => 0, 'message' => '修改成功'));
            }
            else
            {
            	View::ajax(array('code' => 0, 'message' => $this->db->getError()));
            }
        }
        else
        {
            $field = $this->db->find(Q('id'));
            $data = $this->db->getEditData($field['id'],$field['pid']);
            View::with('field',$field)->with('data',$data)->make();
        }
    }

}
